package com.googlecode.framework.web.struts2.interceptor;

import java.text.MessageFormat;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.googlecode.framework.web.user.LoginUserHolder;
import com.googlecode.framework.web.user.UserObject;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * 操作日志拦截器
 *  [sessionid=xxxxxxxxxxxxxxxxxxxx][user=admin] Execute xxxxx.
 *  
 * @author xiayg
 *
 */
public class LoggingInterceptor extends AbstractInterceptor {
    
    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = 3355540107611750614L;
    
    private Logger logger = LoggerFactory.getLogger(getClass());

    /*
     * (non-Javadoc)
     * @see com.opensymphony.xwork2.interceptor.AbstractInterceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
     */
    @Override
    public String intercept(ActionInvocation invocation) throws Exception {
        logInfo(invocation);
        return invocation.invoke();
        
    }
    
    protected void logInfo(ActionInvocation invocation) {
        if (logger.isInfoEnabled()) {
            // user
            HttpSession session = ServletActionContext.getRequest().getSession(false);
            UserObject user = LoginUserHolder.getCurrentUser();
            logger.info(MessageFormat.format("[sessionid={0}][user={1}] Execute {2} {3}.", 
                    session == null ? null : session.getId(),
                    user == null ? null : user.getUsername(), 
                    invocation.getProxy().getNamespace(), 
                    invocation.getProxy().getActionName()));
        }        
    }
}
